const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
  
    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
  }
  
  const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : `0${n}`
  }
  const openImage = (urls, current) => {
    wx.previewImage({
      current,
      urls,
    })
  }
  const openFile = (url) => {
    if (url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".jpeg")) {
      openImage([url], 0)
    } else {
      wx.showLoading({
        title: '下载中',
      })
      wx.downloadFile({
        url,
        success(res) {
          if (res.statusCode === 200) {
            wx.getFileSystemManager().saveFile({
              tempFilePath: res.tempFilePath,
              success(res2) {
                wx.hideLoading()
                wx.openDocument({
                  filePath: res2.savedFilePath,
                  showMenu: true,
                })
              },
              fail(err) {
                console.log("err", err)
              }
            })
          }
        },
        fail(e) {
          wx.hideLoading()
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
    }
  
  }
  const checkIsLogin = (url, id, isTab) => {
    let token = wx.getStorageSync("token"),
      linkUrl;
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1000
      });
    }
    linkUrl = !token ? "../login/index" : `${url}?id=${id}`;
    if (isTab) {
      wx.switchTab({
        url: linkUrl
      })
    } else {
      wx.navigateTo({
        url: linkUrl
      })
    }
  
  }
  
  const wxshowToast = (msg, icon, duration) => {
    wx.showToast({
      title: msg,
      icon: icon || 'none',
      duration: duration || 1000
    });
  }
  const goToLogin = (msg) => {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 1000
    });
    wx.clearStorage()
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/login/index',
      })
    }, 1200);
  
  }

  const formatDateTime = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
  module.exports = {
    formatTime,
    checkIsLogin,
    openFile,
    wxshowToast,
    goToLogin,
    formatDateTime
  }